import 'package:flutter/material.dart';
// import 'photos.dart';
import '../classificationList.dart';
import 'package:flutter/cupertino.dart';
import 'package:firebase_analytics/firebase_analytics.dart';
import '../common/api_service.dart'; // 导入 ApiService 类
import '../common/loading_spinner.dart'; // 导入公共组件
import 'package:cached_network_image/cached_network_image.dart'; //网络图片缓存到本地
// import '../ads/app_open_ad_manager.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import '../ads/ads_unit_id.dart';
import 'package:shared_preferences/shared_preferences.dart';
// import '../main.dart';

class CategoryCardPage extends StatefulWidget {
  const CategoryCardPage({
    super.key,
  });

  @override
  State<CategoryCardPage> createState() => _MyCategoryCardPagePageState();
}

class _MyCategoryCardPagePageState extends State<CategoryCardPage> {
  bool isMember = false;

  List categoryList = [];
  bool isLoading = false;
  static FirebaseAnalytics analytics = FirebaseAnalytics.instance;

  final controller = ScrollController();

  static const _insets = 12.0;
  BannerAd? _inlineAdaptiveAd;
  bool _isLoaded = false;
  AdSize? _adSize;
  // late Orientation _currentOrientation;
  double get _adWidth => MediaQuery.of(context).size.width - (2 * _insets);


  // 调用公共方法
  void fetchData() async {
    setState(() {
      isLoading = true;
    });
    try {
      String url = 'https://apken.oss-us-west-1.aliyuncs.com/goodmorning-es/json/category.json'; // 替换为你的 URL
      List<dynamic> jsonData = await ApiService.fetchJsonData(url);
      // print(jsonData);
      setState(() {
        isLoading = false;
      });
      setState(() {
        categoryList = jsonData[0]['list'];
      });

    } catch (e) {
      setState(() {
        isLoading = false;
      });
      // print(e);
    }
  }

  Future<void> _logScreenView() async {
    await analytics.logScreenView(
      screenName: 'Category Card Page ES',
      screenClass: 'CategoryCardPage_ES',
    );
  }

  Future<int> _getAdStatus() async {
    final prefs = await SharedPreferences.getInstance();
    int status = prefs.getInt('inlineAdStatus') ?? 1;
    return status;
  }

  void _loadInlineAd() async {
    int adStatus = await _getAdStatus();
    if (adStatus != 1) {
      return;
    }

    await _inlineAdaptiveAd?.dispose();
    setState(() {
      _inlineAdaptiveAd = null;
      _isLoaded = false;
    });

    // Get an inline adaptive size for the current orientation.
    AdSize size = AdSize.getCurrentOrientationInlineAdaptiveBannerAdSize(
        _adWidth.truncate());

    _inlineAdaptiveAd = BannerAd(
      // TODO: replace this test ad unit with your own ad unit.
      adUnitId: AdsUnitId.inlineAdaptive,
      size: size,
      request: const AdRequest(),
      listener: BannerAdListener(
        onAdLoaded: (Ad ad) async {
          // print('Inline adaptive banner loaded: ${ad.responseInfo}');

          // After the ad is loaded, get the platform ad size and use it to
          // update the height of the container. This is necessary because the
          // height can change after the ad is loaded.
          BannerAd bannerAd = (ad as BannerAd);
          final AdSize? size = await bannerAd.getPlatformAdSize();
          if (size == null) {
            // print('Error: getPlatformAdSize() returned null for $bannerAd');
            return;
          }

          setState(() {
            _inlineAdaptiveAd = bannerAd;
            _isLoaded = true;
            _adSize = size;
          });
        },
        onAdFailedToLoad: (Ad ad, LoadAdError error) {
          // print('Inline adaptive banner failedToLoad: $error');
          ad.dispose();
        },
      ),
    );
    await _inlineAdaptiveAd!.load();
  }

  Widget _getAdWidget() {
    return OrientationBuilder(
      builder: (context, orientation) {
        if (
            _inlineAdaptiveAd != null &&
            _isLoaded &&
            _adSize != null) {
          return Align(
              child: Container(
                margin: const EdgeInsets.only(top: 12),
            width: _adWidth,
            height: _adSize!.height.toDouble(),
            child: AdWidget(
              ad: _inlineAdaptiveAd!,
            ),
          ));
        }
        // Reload the ad if the orientation changes.
        // if (_currentOrientation != orientation) {
        //   _currentOrientation = orientation;
        //   _loadAd();
        // }
        return Container();
      },
    );
  }

  @override
  void dispose() {
    _inlineAdaptiveAd?.dispose();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();

    _logScreenView();
    _loadInlineAd();

    fetchData();
  }

  @override
  Widget build(BuildContext context) {
    
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: PreferredSize(
        preferredSize: const Size.fromHeight(60),
        child: Container(
          decoration: BoxDecoration(
            color: Colors.white,
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.1),
                offset: const Offset(0, 2),
                blurRadius: 6.0,
              ),
            ],
          ),
          child: AppBar(
            backgroundColor: Colors.white,
            title: const Text(
              'Categoría',
              style:
                   TextStyle(fontFamily: 'OpenSans', color: Colors.black, fontWeight: FontWeight.bold),
            ),
            
          ),
        ),
      ),
      body: isLoading ? 
        const Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            LoadingSpinner()
          ],
        ) 
        :  SingleChildScrollView(
                controller: controller,
            child:  Padding(
        padding: const EdgeInsets.only(left: 16, right: 16, bottom: 16),
        child: Column(
          children: [
            // for (var classificationItem in categoryList)
            //   classification(
            //     classificationItem: classificationItem,
            //   )
            for (var index = 0; index < categoryList.length; index++)
              ...[
                classification(
                  classificationItem: categoryList[index],
                ),
                // 在第二个分类后插入广告
                if (index == 0) 
                  _getAdWidget(), // 替换为你的广告组件
              ]
          ],
        )
      )),
    ) ;
  }
}

class classification extends StatelessWidget {

  Map<String, dynamic> classificationItem;
  classification({
    super.key,
    required this.classificationItem,
  });

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    return Padding(
      padding: const EdgeInsets.only(top: 12),
      child: GestureDetector(
        onTap: () {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => ClassificationListPage(
                classificationItem: classificationItem,
              ),
            ),
          );
        },
        child: Stack(
          children: [
            SizedBox(
              width: width-32,
              height: 150,
              child: ClipRRect(
                borderRadius: BorderRadius.circular(8),
                child:CachedNetworkImage(
                  imageUrl: 'https://apken.oss-us-west-1.aliyuncs.com/goodmorning-es/category/${classificationItem['slug']}.webp',
                  placeholder: (context, url) => const LoadingSpinner(), // 占位图
                  errorWidget: (context, url, error) => const Icon(Icons.error), // 错误图标
                  fit: BoxFit.cover,
                )
              ),
            ),
            Positioned(
              top: 0,
              bottom: 0,
              left: 0,
              right: 0,
              child: Container(
                padding: const EdgeInsets.only(left: 12, right: 12, bottom: 12),
                decoration: const BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topLeft,
                    end: Alignment.bottomLeft,
                    colors: [
                      Color.fromRGBO(0, 0, 0, 0),
                      Color.fromRGBO(0, 0, 0, 0.6)
                    ],
                  ),
                  borderRadius: BorderRadius.only(
                    bottomLeft: Radius.circular(8),
                    bottomRight: Radius.circular(8),
                  ),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    Text(
                      classificationItem['category'],
                      style: const TextStyle(
                          color: Colors.white, fontFamily: 'OpenSans', fontWeight: FontWeight.bold, fontSize: 18),
                    ),
                    const Icon(
                      CupertinoIcons.arrow_right_circle,
                      color: Colors.white,
                      size: 26,
                    )
                  ],
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}
